<?php 
/**
* 
*/

include_once(APPLICATION_PATH."/library/jpgraph/jpgraph.php");
error_reporting(0);


class GraficoController extends Sgit_Controller_Action
{

    protected $_checkZona = FALSE;
    protected $_checkAcceso = FALSE;
    

    public function _begin()
    {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(TRUE);
    }


    public function indexAction()
    {
        $this->_helper->viewRenderer->setNoRender(FALSE);
        $query=$this->getRequest()->getParams();
        $action=$query['grafico'];
        unset($query['controller'],$query['action'],$query['module'],$query['grafico']);
        
        foreach($query as $k => $v)
        {
            $url.='/'.$k.'/'.$v;
        }
        

        $this->view->url='/grafico/'.$action.$url.'/img.jpg';
    }
    
    
 

    public function lecturasContadorAction()
    {
       
        include_once(APPLICATION_PATH."/library/jpgraph/jpgraph_bar.php");
        
        

        $this->_loadModel('Lecturas');
        $this->_loadModel('Contadores');
        
        

        $id=    $this->_getParam('id');
        $tipo=  $this->_getParam('tipo','consumo');
        $width= $this->_getParam('w',800);
        $height=$this->_getParam('h',$width * 0.6);
        
        

        $contador=$this->_model->Contadores->getContador($id);
        
        
        $lecturas= $this->_model->Lecturas->getConsumos($id);
        $lecturas=@array_reverse($lecturas,true);
       


 
       
        switch($tipo){
            case 'lectura':
                $key='lectura';$tit="Consumo Kwh"; $ytitle='kWh';$format='%d';break;
            case 'consumo':
                $key='consumo';$tit="Consumo Kwh"; $ytitle='kWh';$format='%d';break;
            case 'potencia':
                $key='potencia'; $tit="Potencia Kw";$ytitle='kW';$format='%0.2f';break;
            case 'diff':
                $key='incremento_potencia';$tit="Dif Potencia %"; $ytitle='%';$format='%0.2f';break;
            default:
                 $key='consumo';$tit="Consumo Kwh"; $ytitle='kWh';$format='%d';break;
        }
       







        $title=$tit.' '.$contador['nombre'];
        $subtitle=$contador['proyecto'];
        
        
        $i=0;
        
        
        foreach((array)$lecturas as $j => $v)
        {
            
            $f=new Zend_Date($v['date_consumo']);
        	$k=$f->toString('MMM-yy');
            $label[]=$k;
            
            $val[]=($v[$key]) ? $v[$key] : '';
           
        
           
           
            $text1[]=$k;
            $text2[]=$this->view->numEs($v['lectura'],0);
            //if($key=='consumo') $text2.=Utiles::number_formatES($p,0). " kW\n";
        }
    
        $text1=array_reverse($text1);
        $text1=implode(PHP_EOL,$text1);
        $text2=array_reverse($text2);
        $text2=implode(PHP_EOL,$text2);
        

        $step=$this->_step(count($val),$width);
        
        $graph = $this->_graph($width,$height);
        $graph->title->Set(utf8_decode($title));
        $graph->subtitle->Set(utf8_decode($subtitle));
        $graph->SetMargin(75, 150, 30, 80);
        $graph->yaxis->SetTitle($ytitle,'middle'); 
        $graph->xaxis->SetTickLabels($label);
        $graph->xaxis->SetTextLabelInterval($step);


        // Create the bar pot
        $barplot= $this->_barplot($val);
        $barplot->value->Show();
        $barplot->value->SetFont(FF_ARIAL,FS_BOLD,8);
        $barplot->value->SetAngle(90);
        $barplot->value->SetFormat($format);
        $barplot->SetValuePos('center');


        $graph->Add($barplot);
         
         
        
        $txt = new Text($text1);
        $txt->SetPos($width-145, 45);
        $txt->SetFont(FF_ARIAL,FS_ITALIC,7);
        
        $txt2 = new Text($text2);
        $txt2->SetPos($width-90, 45);
        $txt2->SetFont(FF_ARIAL,FS_NORMAL,7);
        
        $txt3 = new Text('Lecturas Kwh');
        $txt3->SetPos($width-145, 30);
        $txt3->SetFont(FF_ARIAL,FS_ITALIC,8);
        
        $graph->AddText($txt); 
        $graph->AddText($txt2); 
        $graph->AddText($txt3);  
         
        $graph->Stroke();
        
    }
    
    
    
    
    
    
    
    
    
    
    public function lecturasContadoresAction()
    {
       
        include_once(APPLICATION_PATH."/library/jpgraph/jpgraph_bar.php");
        
        

        $this->_loadModel('Lecturas');
        $this->_loadModel('Contadores');
        
        

        $ids=    $this->_getParam('id');
        $tipo=  $this->_getParam('tipo','consumo');
        $width= $this->_getParam('w',800);
        $height=$this->_getParam('h',$width * 0.6);
        
       
        $ids=explode(':',$ids);
        
        
                
        //$contador=$this->_model->Contadores->getContador($ids[0]);
        
        foreach($ids as $k => $id)
        {
            $lect= $this->_model->Lecturas->getConsumos($id);
            $lecturas[$k]=@array_reverse($lect,true);
        }
        
        
        

       
        switch($tipo){
            case 'lectura':
                $key='lectura';$tit="Consumo Kwh"; $ytitle='kWh';$format='%d';break;
            case 'consumo':
                $key='consumo';$tit="Consumo Kwh"; $ytitle='kWh';$format='%d';break;
            case 'potencia':
                $key='potencia'; $tit="Potencia Kw";$ytitle='kW';$format='%0.2f';break;
            case 'diff':
                $key='incremento_potencia';$tit="Dif Potencia %"; $ytitle='%';$format='%0.2f';break;
            default:
                 $key='consumo';$tit="Consumo Kwh"; $ytitle='kWh';$format='%d';break;
        }
       




        $title=$tit.' Cuadro';
        $subtitle=$contador['proyecto'];
        
        
        $i=0;
        
        foreach((array)$lecturas as $g => $lectura)
        {
            foreach((array)$lectura as $j => $v)
            {
                $f=new Zend_Date($v['date_consumo']);
            	$k=$f->toString('MMM-yy');
                $label[$j]=$k;
                
                $val[$j]+=$lectura[$j][$key];

            }
        }
    
    
        $val=array_values($val);
        $label=array_values($label);


        $step=$this->_step(count($val),$width);
        
        $graph = $this->_graph($width,$height);
        $graph->title->Set(utf8_decode($title));
        $graph->subtitle->Set(utf8_decode($subtitle));
        $graph->SetMargin(75, 75, 30, 80);
        $graph->yaxis->SetTitle($ytitle,'middle'); 
        $graph->xaxis->SetTickLabels($label);
        $graph->xaxis->SetTextLabelInterval($step);


        // Create the bar pot
        $barplot= $this->_barplot($val);
        $barplot->value->Show();
        $barplot->value->SetFont(FF_ARIAL,FS_BOLD,8);
        $barplot->value->SetAngle(90);
        $barplot->value->SetFormat($format);
        $barplot->SetValuePos('center');


        $graph->Add($barplot);
         
         

        $graph->Stroke();
        
    }
    
    
    
    
    
    
    function _step($nLabel, $width)
    {
        $step = 1;
        if ($width <= 400) {
            if ($nLabel > 20) $step = 2;
            if ($nLabel > 40) $step = 3;
            if ($nLabel > 60) $step = 4;
            if ($nLabel > 80) $step = 5;
        } else {
            if ($nLabel > 40) $step = 2;
            if ($nLabel > 60) $step = 3;
            if ($nLabel > 80) $step = 4;
        }
        return $step;
    }

    
    
    function _graph($width, $height, $nombre = null, $cache = 14000)
    {
        
        if(is_null($nombre)) {
        	$cache = null;
        }else{
        	if (ETAG == true) $this->_etag($nombre);
        	if (CACHEIMAGENES == false){
        		$nombre=null;$cache=null;
        	} 
        }
        
    
        $graph = new Graph($width, $height, $nombre, $cache);
    
        // Adjust the Graph
        $graph->SetScale('textlin');
        $graph->SetFrame(false);
        $graph->SetMargin(75, 25, 30, 80);
        $graph->SetMarginColor('#FFFFFF');
    
    
        // Adjust the legend
        $graph->legend->SetLayout(LEGEND_HOR);
        $graph->legend->Pos(0, 0.99, "right", "bottom");
        $graph->legend->SetFillColor('#F3F3F3');
        $graph->legend->SetFont(FF_ARIAL, FS_NORMAL, 8);
        $graph->legend->SetShadow(false);
        $graph->legend->SetFrameWeight(0);
        $graph->legend->SetLeftMargin(0);
    
    
        //adjust de Y axis
        $graph->yaxis->title->SetFont(FF_FONT1, FS_BOLD, 9);
        $graph->yaxis->SetTitlemargin(62);
        $graph->yaxis->SetLabelFormatCallback(array($this,'_yLabelFormatSinDec'));
        $graph->yaxis->scale->SetGrace(20);
        $graph->yaxis->SetTitleSide(SIDE_LEFT);
    
    
        //adjust de X axis
        $graph->xaxis->title->SetFont(FF_FONT1, FS_BOLD, 11);
        $graph->xaxis->SetLabelAngle(90);
    
        //adjust the grid
        $graph->ygrid->SetFill(true,'#EFEFEF@0.5','#EFEFEF@0.7');
        $graph->xgrid->Show(false);
    
    
        //adjust the background
       	$graph->SetBackgroundGradient('#FFFFFF@0.5', '#EBCCFF@0.5', GRAD_HOR, BGRAD_PLOT);
    
    
        return $graph;
    }

    
    function _etag($nombre)
    {
        $eTag = substr($nombre, 0, -4);
        header('Etag: ' . $eTag);
        header("Cache-Control: public");
        if (trim($_SERVER['HTTP_IF_NONE_MATCH']) == $eTag)
        {
            header("HTTP/1.1 304 Not Modified");
            exit;
        }
    }

	
    function _linePlot($values, $legend = null, $color = 'red', $width = 1, $mark = true)
    {
        $lineplot = new LinePlot($values);
        $lineplot->SetColor($color);
        $lineplot->SetWeight($width);
        if ($mark) {
            $lineplot->mark->SetType(MARK_FILLEDCIRCLE);
            $lineplot->mark->SetFillColor($color);
            $lineplot->mark->SetWidth($width);
        }
        if (!is_null($legend)) $lineplot->SetLegend($legend);
    
        return $lineplot;
    }
    
    
    function _barPlot($values,$color = 'red', $width = 1.0, $showvalue = true)
    {
        $barplot = new BarPlot($values);
    	$barplot->SetColor($color);
    	$barplot->SetWidth($width);
    	$barplot->SetFillColor("$color@0.5");
    	if($showvalue){
    		$barplot->value->Show();
    		$barplot->value->SetFont(FF_ARIAL,FS_BOLD,7);
    		$barplot->value->SetFormat('%d');
    	}
    
        return $barplot;
    }
    
    
    
    function _yLabelFormatSinDec($aLabel)
    {
        return $this->view->numEs($aLabel, 0);
    }
    function _yLabelFormat($aLabel)
    {
        return $this->view->numEs($aLabel, 2);
    }
    function _yLabelFormat4($aLabel)
    {
        return $this->view->numEs($aLabel, 4);
    }

}










/*
function Nrecta_regresion($y)
{

    $otherarray = $y; //Y-array
    $sumX = 0;
    $sumY = 0;
    $sumXX = 0;
    $sumXY = 0;
    $n = count($otherarray); //number of items

    for ($i = 1; $i <= $n; $i++) {
        $myarray[] = $i;
    }


    for ($i = 0; $i < $n; $i++) {
        $sumX += $myarray[$i];
        $sumY += $otherarray[$i];
        $meanX = $sumX / $n;
        $meanY = $sumY / $n;
        $sumXX += pow($myarray[$i], 2);
        $sumXY += ($myarray[$i]) * ($otherarray[$i]);
        $m = ($sumXY - $meanY * $sumX) / ($sumXX - $meanX * $sumX);
        $b = $meanY - $meanX * $m;
    }

    for ($i = 0; $i < $n; $i++) {
        $datay[] = $m * $i + $b;
    }

    return $datay;

}

function Nmedia($y)
{
    $sum = 0;
    for ($i = 0; $i < count($y); $i++) {
        $sum += $y[$i];
    }
    $mean = $sum / count($y);
    return $mean;
}

function Nscala($min, $max)
{

    foreach ($min as $m) {
        if (is_numeric($m)) $mi[] = $m;
    }
    foreach ($max as $m) {
        if (is_numeric($m)) $ma[] = $m;
    }


    $min = $mi;


    $max = max($ma);
    $min = min($min);


    $mx = floor(log($min, 10));


    $pot = pow(10, $mx);


    $gh = floor($min / $pot);
    $min = $gh * $pot;


    $salida['min'] = $min;
    $salida['max'] = $max * 1.05;

    return $salida;

}
*/





